package com.xmall.auth.service.impl;

import com.xmall.auth.define.dict.AccountTypeEnum;
import com.xmall.auth.define.request.PhonePasswordLoginRequest;
import com.xmall.auth.service.ILoginService;
import com.xmall.auth.service.IMemberAccountService;
import com.xmall.auth.service.ISysAccountService;
import com.xmall.define.base.ResultCode;
import com.xmall.exception.XmallException;
import com.xmall.define.dto.login.MemberLoginInfo;
import com.xmall.define.dto.login.SysLoginInfo;
import com.xmall.security.MemberPhonePasswordAuthenticationToken;
import com.xmall.security.SysPhonePasswordAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class LoginServiceImpl implements ILoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private ISysAccountService sysAccountService;

    @Resource
    private IMemberAccountService memberAccountService;

    /**
     * 系统用户：手机号 + 密码登录
     */
    @Override
    public SysLoginInfo sysLoginWithPhonePassword(PhonePasswordLoginRequest request) {
        SysLoginInfo loginInfo = (SysLoginInfo)this.authenticate(new SysPhonePasswordAuthenticationToken(request.getPhone(), request.getPassword()));

        if(null == loginInfo){
            throw new XmallException(ResultCode.AUTH_LOGIN_ERROR);
        }

        //更新登录时间
        loginInfo.setLastLoginTime(sysAccountService.updateLastLoginTime(loginInfo.getUserId(), AccountTypeEnum.PHONE.getType()));
        return loginInfo;
    }

    /**
     * 普通用户：手机号 + 密码登录
     */
    @Override
    public MemberLoginInfo memberLoginWithPhonePassword(PhonePasswordLoginRequest request) {
        MemberLoginInfo loginInfo = (MemberLoginInfo)this.authenticate(new MemberPhonePasswordAuthenticationToken(request.getPhone(), request.getPassword()));

        if(null == loginInfo){
            throw new XmallException(ResultCode.AUTH_LOGIN_ERROR);
        }

        //更新登录时间
        loginInfo.setLastLoginTime(memberAccountService.updateLastLoginTime(loginInfo.getUserId(), AccountTypeEnum.PHONE.getType()));
        return loginInfo;
    }

    /**
     * 手机号登录
     */
    private Object authenticate(Authentication token){
        try {
            Authentication authenticate = authenticationManager.authenticate(token);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            return authenticate.getDetails();
        }catch (AuthenticationException authenticationException){
            throw new XmallException(ResultCode.AUTH_LOGIN_ERROR);
        }
    }

}
